import os

from django.conf import settings

def add_class(self,attributes,*classnames):
    classes = set(attributes.get('class',u'').split())
    output  = dict(attributes)
    for classname in classnames:
        classes.add(classname)
    output['class'] = u' '.join(classes)
    return output

def image_attributes(self,attributes):
    output = []
    output.append(self.table_common_attributes(attributes))
    output.append(self.render_attribute('src', attributes['src']))
    output.append(self.render_attribute('alt', attributes['alt']))
    return u''.join(output)

def render_image(self,src=None,alt=None,attributes={}):
    if src and alt:
        src = src.lstrip('/')
        if os.path.isfile(os.path.join(settings.MEDIA_ROOT,src)):
            src = '{0}{1}'.format(settings.MEDIA_URL,src)
        elif self.theme.has_medium(src):
            src = self.theme.get_medium(src).url
        else:
            return u''
        attributes.update({'src':src,'alt':alt})
        return self.render_tag('img',attributes=attributes,render_attributes=self.image_attributes,
                               block_tag=False)
    return u''

def render_tag(self,tag,content=None,attributes={},render_content=None,render_attributes=None,
               allow_empty=False,block_tag=True):
    if render_content:
        content = render_content(content)
    attrs = render_attributes(attributes) if render_attributes else self.common_attributes(attributes)
    if not block_tag:
        return self.safe(u'\n<{tag}{attrs}/>'.format(tag=tag,attrs=attrs))
    if content or allow_empty:
        content = self.escape(content) if content else u''
        return self.safe(u'\n<{tag}{attrs}>{content}</{tag}>'.format(tag=tag,attrs=attrs,
                                                                   content=content))
    return u''

